package sq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sq.dao.Cart;
import sq.service.CartService;
import sq.vo.BaseRespVO;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: sunquan
 * @Date: 2018/3/5
 * @Time: 14:13
 */
@RestController
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping(value = "/cart/put")
    public BaseRespVO addCart(@RequestParam(name = "foodId") Integer foodId,
                              @RequestParam(name = "price") double price,
                              @RequestParam(name = "buyNumber") Integer buyNumber,
                              HttpServletRequest request) {
        BaseRespVO baseRespVO = new BaseRespVO();
        String flag = cartService.addFoodByCart(foodId, price, buyNumber, request);
        if (flag == "0") {
            baseRespVO.setCode("0");
            baseRespVO.setMsg("添加购物车成功");
        } else if (flag == "1") {
            baseRespVO.setCode("1");
            baseRespVO.setCode("未登录，请先登录！");
        }
        return baseRespVO;
    }

    @PostMapping(value = "/cart")
    public BaseRespVO showCart(HttpServletRequest request) {
        BaseRespVO baseRespVO = new BaseRespVO();
        ArrayList<Cart> cartList = null;
        cartList = (ArrayList<Cart>) cartService.findCart(request);
        baseRespVO.setCode("0");
        baseRespVO.setMsg("查询成功");
        baseRespVO.setData(cartList);
        return baseRespVO;
    }

    @PostMapping(value = "/cart/delete/{cartId}")
    public BaseRespVO deleteCart(@PathVariable(name = "cartId") Integer cartId) {
        BaseRespVO baseRespVO = new BaseRespVO();
        cartService.deletCart(cartId);
        baseRespVO.setCode("0");
        baseRespVO.setMsg("删除成功");
        return baseRespVO;
    }

    /**
     * 删除多个id
     * @param checkedId
     * @return
     */
    @PostMapping(value = "/cart/del")
    public BaseRespVO delCart(String checkedId) {
        BaseRespVO baseRespVO = new BaseRespVO();
        cartService.delCart(checkedId);
        baseRespVO.setCode("0");
        baseRespVO.setMsg("删除成功");
        return baseRespVO;
    }

    @PostMapping(value = "/cart/delete/")
    public BaseRespVO deleteAllCart(String checkedId,HttpServletRequest request) {
        BaseRespVO baseRespVO = new BaseRespVO();
        cartService.deleteAllCart(checkedId,request);
        baseRespVO.setCode("0");
        baseRespVO.setMsg("删除成功");
        return baseRespVO;
    }

}
